package com.ts.proj.json;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerBorderImpl;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerColorImpl;
import com.ts.base.controller.BaseController;
import com.ts.proj.entity.excelEntity.*;
import com.ts.proj.service.MeasureService;
import com.ts.util.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class ReportJson extends BaseController {


    @Autowired
    private MeasureService measureService;
    /**
     * 显示list
     * @return
     */
    @RequestMapping(value = "/report-czjl/{flag}/{factory}")
    public Map<String,Object> reportCZJLList(@PathVariable("flag") Integer flag,@PathVariable("factory") Integer factory){
        PageData pd = this.getPageData();

        String from = DateUtil.getDay() + " 00:00:00";
        String to = DateUtil.getDay() + " 23:59:59";
//        String month = CommonUtils.month(new Date());
//
        if(null!=pd.get("from")&&!"".equals(pd.get("from").toString())&&!"undefined".equals(pd.get("from").toString())){
            from = pd.getString("from");
        }
        if(null!=pd.get("to")&&!"".equals(pd.get("to").toString())&&!"undefined".equals(pd.get("to").toString())){
            to = pd.getString("to");
        }
        List<MeasureCZJLVOExcel> list = new ArrayList<>();
        list = measureService.czjl(flag, factory,from,to);
        PageData pageData = this.getPageData();
        pageData.put("rows", list);
        return pageData;
    }


    @RequestMapping(value = "/report-list/{flag}/{factory}")
    public Map<String,Object> reportList(@PathVariable("flag") String flag,@PathVariable("factory") String factory){
        PageData pd = this.getPageData();
        String date = DateUtil.getDay();
        String toDate = DateUtil.getDay();
        Date month = new Date();

        if(null!=pd.get("date")&&!"".equals(pd.get("date").toString())&&!"undefined".equals(pd.get("date").toString())){
            date = pd.getString("date");
            try{
                month = CommonUtils.str2Date(date);
            }catch (Exception e){
                month = new Date();
            }
        }
        if(null!=pd.get("toDate")&&!"".equals(pd.get("toDate").toString())&&!"undefined".equals(pd.get("toDate").toString())){
            toDate = pd.getString("toDate");
        }
        List<PageData> list = new ArrayList<>();
        String fac = factory.equals("yd") ? "益达" : "益隆";
//        if(fac.equals("益达")){
//            if("IN".equals(flag)){
//                list = measureService.reportInByMoveTypeYD(fac, date, CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month),toDate);
//            }else if("OUT".equals(flag)){
//                list = measureService.reportOutByMoveType(fac, date,CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month),toDate);
//            }
//        }else{
            if("IN".equals(flag)){
                list = measureService.reportInByMoveType(fac, date, CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month));
            }else if("OUT".equals(flag)){
                list = measureService.reportOutByMoveType(fac, date,CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month));
            }
//        }
        PageData pageData = this.getPageData();
        pageData.put("rows", list);
        return pageData;
    }

    @RequestMapping(value = "/month-list")
    public Map<String,Object> reportList(){
        PageData pd = this.getPageData();
        String date = DateUtil.getDay();
        Date month = new Date();
        if(null!=pd.get("from")&&!"".equals(pd.get("from").toString())&&!"undefined".equals(pd.get("from").toString())){
            date = pd.getString("from");
            try{
                month = CommonUtils.str2Date(date);
            }catch (Exception e){
                month = new Date();
            }
        }
        List<MonthEntityExcel> list = new ArrayList<>();
        String fac = pd.get("fac").toString();

        list = measureService.month(fac, CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month));
        PageData pageData = this.getPageData();
        pageData.put("rows", list);
        return pageData;
    }

    @RequestMapping(value = "/out-month-list")
    public Map<String,Object> outReportList(){
        PageData pd = this.getPageData();
        String date = DateUtil.getDay();
        Date month = new Date();
        if(null!=pd.get("from")&&!"".equals(pd.get("from").toString())&&!"undefined".equals(pd.get("from").toString())){
            date = pd.getString("from");
            try{
                month = CommonUtils.str2Date(date);
            }catch (Exception e){
                month = new Date();
            }
        }
        List<MonthEntityExcel> list = new ArrayList<>();
        String fac = pd.get("fac").toString();

        list = measureService.outMonth(fac, CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month));
        PageData pageData = this.getPageData();
        pageData.put("rows", list);
        return pageData;
    }



    @RequestMapping(value = "/in-month-download")
    public void inMonthDownload(HttpServletResponse response) throws IOException {
        PageData pd = this.getPageData();
        String date = DateUtil.getDay();
        Date month = new Date();
        if(null!=pd.get("from")&&!"".equals(pd.get("from").toString())&&!"undefined".equals(pd.get("from").toString())){
            date = pd.getString("from");
            try{
                month = CommonUtils.str2Date(date);
            }catch (Exception e){
                month = new Date();
            }
        }
        List<MonthEntityExcel> list = new ArrayList<>();
        String fac = pd.get("fac").toString();
        list = measureService.month(fac, CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month));
        ExportParams params = new ExportParams("进厂月报表","统计单", ExcelType.XSSF);
        params.setStyle(ExcelExportStylerBorderImpl.class);//设置样式,自定义实现IExcelDataHandler<T>
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-disposition", "attachment; filename=" + new String(DateUtil.getID().getBytes("gb2312"), "ISO-8859-1") + ".xls");
        ServletOutputStream outStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(params, MonthEntityExcel.class, list);
        try {
            outStream = response.getOutputStream();
            workbook.write(outStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outStream.close();
        }

    }

    @RequestMapping(value = "/out-month-download")
    public void outMonthDownload(HttpServletResponse response) throws IOException {
        PageData pd = this.getPageData();
        String date = DateUtil.getDay();
        Date month = new Date();
        if(null!=pd.get("from")&&!"".equals(pd.get("from").toString())&&!"undefined".equals(pd.get("from").toString())){
            date = pd.getString("from");
            try{
                month = CommonUtils.str2Date(date);
            }catch (Exception e){
                month = new Date();
            }
        }
        List<MonthEntityExcel> list = new ArrayList<>();
        String fac = pd.get("fac").toString();
        list = measureService.outMonth(fac, CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month));
        ExportParams params = new ExportParams("出厂月报表","统计单", ExcelType.XSSF);
        params.setStyle(ExcelExportStylerBorderImpl.class);//设置样式,自定义实现IExcelDataHandler<T>
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-disposition", "attachment; filename=" + new String(DateUtil.getID().getBytes("gb2312"), "ISO-8859-1") + ".xls");
        ServletOutputStream outStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(params, MonthEntityExcel.class, list);
        try {
            outStream = response.getOutputStream();
            workbook.write(outStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outStream.close();
        }

    }



    @RequestMapping(value = "/zcb-list/{page}/{size}")
    public Map<String,Object> zzbReport(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageData temp = this.getPageData();
        String sql = "";
        if(null!=temp.get("date")&&!"undefined".equals(temp.get("date"))&&!"".equals(temp.get("date"))){
            sql += " and DATE(measure.gross_weight_date ) >= '"+temp.getString("date")+"'   ";
        }
        if(null!=temp.get("to")&&!"undefined".equals(temp.get("to"))&&!"".equals(temp.get("to"))){
            sql += " and DATE(measure.gross_weight_date ) <= '"+temp.getString("to")+"'   ";
        }
        PageData pageData = new PageData();
        long count = measureService.zcbCount(sql);
        List<ZCBEntityExcel> zcb = measureService.zcb(page-1, size,sql);
        pageData.put("total",count);
        pageData.put("rows", zcb);
        return pageData;
    }

    @RequestMapping("/zcb-download")
    public void export(HttpServletResponse response){
            PageData temp = this.getPageData();
        String sql = "";
        if(null!=temp.get("from")&&!"undefined".equals(temp.get("from"))&&!"".equals(temp.get("from"))){
            sql += " and DATE(measure.gross_weight_date ) >= '"+temp.getString("from")+"'   ";
        }
        if(null!=temp.get("to")&&!"undefined".equals(temp.get("to"))&&!"".equals(temp.get("to"))){
            sql += " and DATE(measure.gross_weight_date ) <= '"+temp.getString("to")+"'   ";
        }
        long count = measureService.zcbCount(sql);
        List<ZCBEntityExcel> zcb = measureService.zcb(0, Integer.valueOf(String.valueOf(count)),sql);
        EasyPoiUtil.exportExcel(zcb,"政府公示货运源头单位车辆装载登记表","治超台账",ZCBEntityExcel.class, DateUtil.getID()+".xls",response);
    }

     @RequestMapping("/report-czjl-download")
    public void exportCZJL(HttpServletResponse response) throws IOException {
        PageData pd = this.getPageData();
         String from = DateUtil.getDay() + " 00:00:00";
         String to = DateUtil.getDay() + " 23:59:59";
//
         if(null!=pd.get("from")&&!"".equals(pd.get("from").toString())&&!"undefined".equals(pd.get("from").toString())){
             from = pd.getString("from");
         }
         if(null!=pd.get("to")&&!"".equals(pd.get("to").toString())&&!"undefined".equals(pd.get("to").toString())){
             to = pd.getString("to");
         }
         List<MeasureCZJLVOExcel> zcb = measureService.czjl(0, 1,from,to);
         ExportParams params = new ExportParams("称重统计汇总单","统计单", ExcelType.XSSF);
         params.setStyle(ExcelExportStylerBorderImpl.class);//设置样式,自定义实现IExcelDataHandler<T>
         response.reset();
         response.setContentType("application/x-msdownload");
         response.setHeader("Content-disposition", "attachment; filename=" + new String(DateUtil.getID().getBytes("gb2312"), "ISO-8859-1") + ".xls");
         ServletOutputStream outStream = null;
         Workbook workbook = ExcelExportUtil.exportExcel(params, MeasureCZJLVOExcel.class, zcb);
         try {
             outStream = response.getOutputStream();
             workbook.write(outStream);
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             outStream.close();
         }

    }



    @RequestMapping("/daily-download/{flag}/{factory}")
    public void dailyExport(HttpServletResponse response,@PathVariable("flag") String flag,@PathVariable("factory") String factory) throws IOException {
        PageData pd = this.getPageData();
        String date = DateUtil.getDay();
        Date month = new Date();
        if(null!=pd.get("from")&&!"".equals(pd.get("from").toString())&&!"undefined".equals(pd.get("from").toString())){
            date = pd.getString("from");
            try{
                month = CommonUtils.str2Date(date);
            }catch (Exception e){
                month = new Date();
            }
        }
        List<PageData> list = new ArrayList<>();
        String fac = "";
        String title = "";
        if(factory.equals("yd")){
            fac = "益达";
            title = "生产指挥中心磅房";
        }else if(factory.equals("yl")){
            fac = "益隆";
            title = "仪表车间磅房";
        }

        if("IN".equals(flag)){
            list = measureService.reportInByMoveType(fac, date, CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month));
            title += "进厂物资日报表"+date;
        }else if("OUT".equals(flag)){
            list = measureService.reportOutByMoveType(fac, date, CommonUtils.ylLeftMonth(month), CommonUtils.ylRightMonth(month));
            title += "出厂物资日报表"+date;
        }
        List<ReportExcel> excelList = new ArrayList<>();
        for(PageData pageData : list){
            ReportExcel excel = new ReportExcel();
            excel.setMaterial(objIsNull(pageData.get("material")));
            excel.setSupplier(objIsNull(pageData.get("supplier")));
            excel.setCars(objIsNull(pageData.get("cars")));
            excel.setDialy(objIsNull(pageData.get("dialy")));
            excel.setAllgross(objIsNull(pageData.get("allgross")));
            excel.setDaysuttle(objIsNull(pageData.get("daysuttle")));
            excel.setAllsuttle(objIsNull(pageData.get("allsuttle")));
            excelList.add(excel);
        }
        ExportParams params = new ExportParams(title,"日报表", ExcelType.XSSF);
        params.setStyle(ExcelExportStylerBorderImpl.class);//设置样式,自定义实现IExcelDataHandler<T>
        response.reset();
        response.setContentType("application/x-msdownload");
        String fileName = factory + DateUtil.getID() ;

        response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
        ServletOutputStream outStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(params, ReportExcel.class, excelList);
        try {
            outStream = response.getOutputStream();
            workbook.write(outStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outStream.close();
        }

    }

    private  String objIsNull(Object obj){
        if(obj==null){
            return "";
        }else{
            return obj.toString();
        }
    }

}
